package com.yj.idempotence.dynamicDataSource;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 需要通过AOP进行动态代理，读取数据源注解，进行数据源切换
 */
@Aspect
@Component
@Order(1)
@Slf4j
public class DataSourceAOP {


    @Pointcut(value = "@annotation(com.yj.idempotence.dynamicDataSource.ChooseDataSource)")
    public void dataSourcePointCut(){

    }

    @Around("dataSourcePointCut()")
    public Object aroud(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        ChooseDataSource ds = method.getAnnotation(ChooseDataSource.class);
        // 通过判断 DataSource 中的值来判断当前方法应用哪个数据源
        DynamicDataSource.setThreadLocal(ds.value());
        log.debug("set datasource is " + ds.value());
        try {
            return joinPoint.proceed();
        } finally {
            DynamicDataSource.removeThreadLocal();
            log.debug("clean datasource");
        }
    }

}
